﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Reflection;
using System.Text;
using System.Data;

/// <summary>
///JsonHelp 的摘要说明
/// </summary>
public class ToJson
{
    public ToJson()
    {

    }

    /// <summary>
    /// datatable转json，for grid
    /// </summary>
    /// <param name="total">总条数</param>
    /// <param name="jsonName">名字，一般为 rows</param>
    /// <param name="dt">数据源</param>
    /// <returns></returns>
    public static string DataTableToJson(string total, string jsonName, DataTable dt)
    {
        StringBuilder Json = new StringBuilder();
        Json.Append("{\"total\":" + total + ",\"" + jsonName + "\":[");
        if (dt.Rows.Count > 0)
        {
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                Json.Append("{");
                for (int j = 0; j < dt.Columns.Count; j++)
                {
                    Json.Append("\"" + dt.Columns[j].ColumnName.ToString().Trim() + "\":\"" + dt.Rows[i][j].ToString().Trim() + "\"");
                    if (j < dt.Columns.Count - 1)
                    {
                        Json.Append(",");
                    }
                }
                Json.Append("}");
                if (i < dt.Rows.Count - 1)
                {
                    Json.Append(",");
                }
            }
        }
        else
        {
            DataRow dr = dt.NewRow();
            Json.Append("{");
            for (int j = 0; j < dt.Columns.Count; j++)
            {
                Json.Append("\"" + dt.Columns[j] + "\":\"" + " " + "\"");
                if (j < dt.Columns.Count - 1)
                {
                    Json.Append(",");
                }
            }
            Json.Append("}");
        }
        Json.Append("]}");
        return Json.ToString();
    }
    /// <summary>
    /// 根据DataTable生成Json树结构,不是异步
    /// </summary>
    /// <param name="tabel">数据源</param>
    /// <param name="idCol">ID列</param>
    /// <param name="txtCol">Text列</param>
    /// <param name="rela">关系字段</param>
    /// <param name="pId">父ID</param>
    /// GetTreeJsonByTable(datatable, "id", "title", "pid", "0");
    public static string GetTreeJsonByTable(DataTable tabel, string idCol, string txtCol, string rela, object pId)
    {
        StringBuilder result = new StringBuilder();
        StringBuilder sb = new StringBuilder();
        result.Append(sb.ToString());
        sb.Clear();
        if (tabel.Rows.Count > 0)
        {
            sb.Append("[");
            string filer = string.Format("{0}='{1}'", rela, pId);
            DataRow[] rows = tabel.Select(filer);
            if (rows.Length > 0)
            {
                foreach (DataRow row in rows)
                {
                    sb.Append("{\"id\":\"" + row[idCol] + "\",\"text\":\"" + row[txtCol] + "\",\"state\":\"open\"");
                    if (tabel.Select(string.Format("{0}='{1}'", rela, row[idCol])).Length > 0)
                    {
                        sb.Append(",\"children\":");
                        sb.Append(GetTreeJsonByTable(tabel, idCol, txtCol, rela, row[idCol]));
                        result.Append(sb.ToString());
                        sb.Clear();
                    }
                    result.Append(sb.ToString());
                    sb.Clear();
                    sb.Append("},");
                }
                sb = sb.Remove(sb.Length - 1, 1);
            }
            sb.Append("]");
            result.Append(sb.ToString());
            sb.Clear();
        }
        return result.ToString();
    }
    /// <summary>
    /// 根据DataTable生成Json树结构,异步
    /// </summary>
    /// <param name="tabel">数据源</param>
    /// <param name="idCol">ID列</param>
    /// <param name="txtCol">Text列</param>
    /// <param name="rela">关系字段</param>
    /// <param name="pId">父ID</param>
    /// <param name="urlCol">url连接，为空则不会赋值</param>
    /// GetTreeJsonByTable(datatable, "id", "title", "pid", "0");
    public static string GetTreeJsonByTableAsync(DataTable tabel, string idCol, string txtCol, string rela, object pId,string urlCol,string[] SelectColoums)
    {
        StringBuilder result = new StringBuilder();
        StringBuilder sb = new StringBuilder();
        result.Append(sb.ToString());
        sb.Clear();
        string filer = string.Format("{0}='{1}'", rela, pId);
        DataRow[] rows = tabel.Select(filer);
        if (tabel.Rows.Count > 0 && rows.Count() > 0)
        {
            sb.Append("[");
            if (rows.Length > 0)
            {
                foreach (DataRow row in rows)
                {
                    string state = row["haveC"].ToString()=="haveC"?"closed":"open";
                    string url = row[urlCol] != null ? row[urlCol].ToString() : "";
                    sb.Append("{\"id\":\"" + row[idCol] + "\",\"text\":\"" + row[txtCol] + "\",\"iconCls\":\"" + row["MenuIcon"] + "\",\"state\":\"" + state + "\",\"attributes\":{\"url\":\"" + url + "\",\"id\": \"" + row[idCol] + "\"}");
                    foreach (string s in SelectColoums)
                    {
                        sb.Append(",\""+s+"\":\""+row[s]+"\"");
                    }
                    if (tabel.Select(string.Format("{0}='{1}'", rela, row[idCol])).Length > 0)
                    {
                        sb.Append(",\"children\":");
                        sb.Append(GetTreeJsonByTableAsync(tabel, idCol, txtCol, rela, row[idCol], urlCol,SelectColoums));
                        result.Append(sb.ToString());
                        sb.Clear();
                    }
                    result.Append(sb.ToString());
                    sb.Clear();
                    sb.Append("},");
                }
                sb = sb.Remove(sb.Length - 1, 1);
            }
            sb.Append("]");
            result.Append(sb.ToString());
            sb.Clear();
        }
        else
        {
            return "[{\"id\":\"2\",\"text\":\"text2\",\"state\":\"closed\"}]";
        }
        return result.ToString();
    }



    //List转成json
    public static string ObjectToJson<T>(string jsonName, IList<T> IL)
    {
        StringBuilder Json = new StringBuilder();
        Json.Append("{\"" + jsonName + "\":[");
        if (IL.Count > 0)
        {
            for (int i = 0; i < IL.Count; i++)
            {
                T obj = Activator.CreateInstance<T>();
                Type type = obj.GetType();
                PropertyInfo[] pis = type.GetProperties();
                Json.Append("{");
                for (int j = 0; j < pis.Length; j++)
                {
                    Json.Append("\"" + pis[j].Name.ToString() + "\":\"" + pis[j].GetValue(IL[i], null) + "\"");
                    if (j < pis.Length - 1)
                    {
                        Json.Append(",");
                    }
                }
                Json.Append("}");
                if (i < IL.Count - 1)
                {
                    Json.Append(",");
                }
            }
        }
        Json.Append("]}");
        return Json.ToString();
    }




}